﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Krile.Kernel.Data;
using Krile.Kernel.WindowsEx;

namespace Krile.Forms.Dialogs.Editor.SearchData
{
    public partial class QueryEditor : Form
    {
        public SearchDataCluster Cluster { get; set; }

        public QueryEditor()
        {
            InitializeComponent();
        }

        private void QueryEditor_Load(object sender, EventArgs e)
        {
            this.queryText.Text = Query.QueryEvaluator.ToQuery(Query.QueryEvaluator.SimplifyCluster(this.Cluster));
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            if (ValidateFilter())
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }

        private void testButton_Click(object sender, EventArgs e)
        {
            if (ValidateFilter())
            {
                MessageBoxEx.ShowDialog(this, "OK", "Krile Query", MessageBoxEx.MessageBoxExButtons.OK, MessageBoxEx.MessageBoxExIcon.Information);
            }
        }

        private bool ValidateFilter()
        {
            try
            {
                this.Cluster = Query.QueryEvaluator.ToFilter(this.queryText.Text);
                return true;
            }
            catch (Exception e)
            {
                MessageBoxEx.ShowDialog(this, "Invalid query", e.Message, "Krile Query", MessageBoxEx.MessageBoxExButtons.Close, MessageBoxEx.MessageBoxExIcon.Error);
                return false;
            }
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}
